package cn.myjerry.thread.syn;

/**
 * 
 * @author Jerry
 *
 */

public class SynDemo02 {
	public static void main(String[] args) {
		JvmThread j1 = new JvmThread(10);
		JvmThread j2 = new JvmThread(50);
		
		j1.start();
		j2.start();
	}
}

class JvmThread extends Thread {
	private long time;
	
	public JvmThread() {
		super();
	}

	public JvmThread(long time) {
		super();
		this.time = time;
	}

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + " --> " + Jvm.getInstance(time));
	}
	
}
class Jvm {
	private static Jvm instance = null;
	
	private Jvm() {}
	
	public static Jvm getInstance(long time) {
		if(instance == null) {
			synchronized(Jvm.class) {
				if (instance == null) {
					try {
						Thread.sleep(time);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					instance = new Jvm();
				}
			}
		}
		return instance;
	}
}

class Jvm3 {
	private static Jvm3 instance = null;
	
	private Jvm3() {}
	
	public static Jvm3 getInstance(long time) {
		synchronized(Jvm.class) {
			if (instance == null) {
				try {
					Thread.sleep(time);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				instance = new Jvm3();
			}
			return instance;
		}
	}
}

class Jvm2 {
	private static Jvm2 instance = null;
	
	private Jvm2() {}
	
	public static synchronized Jvm2 getInstance(long time) {
		if(instance == null) {
			try {
				Thread.sleep(time);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			instance = new Jvm2();
		}
		return instance;
	}
}

/**
 * 单例设计模式
 * 确保一个类只有一个对象
 * 懒汉式
 * 1）构造器私有化，避免外部直接创建对象
 * 2）声明一个私有的静态变量
 * 3）创建一个对外的公共的静态方法访问该变量，如果变量没有对象，创建该对象
 *
 */

class Jvm1 {
	private static Jvm1 instance = null;
	
	private Jvm1() {}
	
	public static Jvm1 getInstance(long time) {
		if(instance == null) {
			try {
				Thread.sleep(time);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			instance = new Jvm1();
		}
		return instance;
	}
}